import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import 'package:xlsk/api/index.dart';
import 'package:xlsk/config/easyLoading.dart';
import 'package:xlsk/routes/xlsk_router.dart';
import 'package:xlsk/store/model/userInfo.dart';
import 'package:xlsk/utils/storage.dart';

class Login {
  factory Login(){
    final _instance = Login._();
    return _instance;
  }
  Login._();

  sendCode(context,path,data) async{  //发送验证码
    var res = await Request(context).post(path,data);
    var code = res['code'] is String?num.parse(res['code']):res['code'];
    if(code == 200){
      SetEasyLoading(displayDuration: 800);
      EasyLoading.showSuccess('发送成功');
    }else if(code == 100){ // 请稍后发送
      // XlskRouter.back(context); //修改：不返回上一页了
    }
    res['code'] = code;
    return res;
  }
  
  void submitCode(context,path,data) async{ //提交验证码,登入
    var res = await Request(context).post(path,data);
    var userInfo = res['data'];
    // print('res');print(res);print('userInfo');print(userInfo);
    SetEasyLoading(displayDuration: 800);
    EasyLoading.showSuccess('登录成功');
    //保存userInfo
    var provider = Provider.of<UserInfo>(context,listen: false);
    provider.saveUserInfo(userInfo);
    // 存到内存中
    Storage.setString('userInfo', userInfo);
    // 回首页
    XlskRouter.goRemoveUntil(context, '/');
  }
}